package com.xiaohong.websocket.controller;

import com.alibaba.fastjson.JSON;
import com.xiaohong.mq.feign.MqSenderFeign;
import com.xiaohong.mq.feign.PullMessageFeign;
import com.xiaohong.mq.pojo.ReceiveMsg;
import com.xiaohong.mq.pojo.SendMsg;
import com.xiaohong.user.feign.ChatFriendFeign;
import com.xiaohong.user.feign.ChatUserFeign;
import com.xiaohong.user.pojo.Friend;
import com.xiaohong.user.pojo.User;
import com.xiaohong.websocket.server.ChatCentre;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : xiaohong
 * @date : 2021/4/14 8:43
 */
@RestController
@CrossOrigin
@RequestMapping("/chatCentre")
public class ChatCentreController {

    @Autowired
    private ChatCentre chatCentre;

    @Autowired
    private MqSenderFeign mqSenderFeign;

    @Autowired
    private PullMessageFeign pullMessageFeign;

    @Autowired
    private ChatFriendFeign chatFriendFeign;

    @Autowired
    private ChatUserFeign chatUserFeign;

    // 获取连接者消息
    @GetMapping("/getUserInfo/{userId}")
    public Result getUserInfo (@PathVariable String userId){
        return new Result(true, StatusCode.OK,"获取连接者消息成功",ChatCentre.chatCentreClients.get(userId));
    }

    // 获取连接人数
    @GetMapping("/getNumber")
    public Result getNumer() {
        return new Result(true, StatusCode.OK,"获取连接人数成功",ChatCentre.chatCentreClients.size());
    }

    /**
     * 获取指定用户连接状态
     * @param cid
     * @return 0 用户离线 1 用户在线 2 用户隐身 3用户不存在
     */
    @GetMapping("/status/{cid}")
    public Result<Integer> getStatus(@PathVariable Long cid){
        if (chatCentre.chatCentreClients.get(cid) != null){
            ChatCentre webSocketCentre = chatCentre.chatCentreClients.get(cid);
            if(!webSocketCentre.session.isOpen()){
                return new Result<Integer>(true, StatusCode.OK,"用户离线",0);
            }else {
                return new Result<Integer>(true, StatusCode.OK,"用户在线",1);
            }
        }else {
            // 看看数据库有没有这个人的信息
            User data = chatUserFeign.findById(cid).getData();
            if (data != null){
                // 有这人 当隐身处理
                return new Result<Integer>(true, StatusCode.OK,"用户隐身",2);
            }else{
                // 用户不存在
                return new Result<Integer>(true, StatusCode.OK,"用户不存在",3);
            }
        }
    }


    /**
     * 向指定对象发送消息
     * @return
     */
    @PostMapping("/send")
    public Result sendMessage(@RequestBody SendMsg sendMsg) throws IOException {
        // 判断接收者状态
        try {

            Long from = Long.parseLong(sendMsg.getSender());
            Long to = Long.parseLong(sendMsg.getReceiver());

            Friend fd = new Friend();
            fd.setUserId(from);
            fd.setFriendId(to);

            if(!chatFriendFeign.isFriend(fd).getData()){
                // 不是好友，直接返回
                if (getStatus(from).getData() == 1){
//                    chatCentre.chatCentreClients.get(from).session.getBasicRemote().sendText(to+ "不是你的好友哦");
//                    mqSenderFeign.send(JSON.toJSONString(sendMsg));
                    return new Result(true,StatusCode.ERROR,"不是你的好友哦",sendMsg);
                }else {
                    System.out.println("发送者离线");
                }
            }else if (getStatus(to).getData() == 0){
                //用户离线 返回到mq
                sendMsg.setStatus(true);
                if (getStatus(from).getData() == 1){
//                    chatCentre.chatCentreClients.get(from).session.getBasicRemote().sendText(to+ "  用户离线");
                    mqSenderFeign.send(JSON.toJSONString(sendMsg));
                    return new Result(true,StatusCode.OK,"用户离线",sendMsg);
                }else {
                    System.out.println("发送者离线");
                }
            }else if (getStatus(to).getData() == 1){
                // 用户在线
                //判断发送者
                sendMsg.setStatus(true);
                if (getStatus(from).getData() == 1){
                    chatCentre.chatCentreClients.get(to).session.getBasicRemote().sendText(JSON.toJSONString(sendMsg));
                    // 回执
//                    chatCentre.chatCentreClients.get(from).session.getBasicRemote().sendText("发送成功");
                    return new Result(true,StatusCode.OK,"发送成功",sendMsg);
                }else {
                    System.out.println("发送者离线");
                }
            }else if (getStatus(to).getData() == 2){
                // 用户隐身 当离线处理
                sendMsg.setStatus(true);
                if (getStatus(from).getData() == 1){
                    chatCentre.chatCentreClients.get(to).session.getBasicRemote().sendText(JSON.toJSONString(sendMsg));
                    return new Result(true,StatusCode.OK,"发送成功",sendMsg);
                }else {
                    System.out.println("发送者离线");
                }
            }else if(getStatus(to).getData() == 3){
                // 用户不存在
                if (getStatus(from).getData() == 1){
                    // 用户不存在
                    return new Result(true,StatusCode.ERROR,"用户不存在",sendMsg);
                }else {
                    System.out.println("发送者离线");
                }
            }

            return new Result(true,StatusCode.ERROR,"发送者离线",sendMsg);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(true,StatusCode.ERROR,"发送失败",sendMsg);
        }
    }


    /**
     * 将未读消息存储MQ
     * @param message
     * @return
     */
    @GetMapping("/mqSend")
    public String send(@RequestParam SendMsg message){
        mqSenderFeign.send(JSON.toJSONString(message));
        return "发送成功";
    }

//    /**
//     * Nack获取所有MQ消息
//     * @return
//     */
//    @GetMapping("/mqPullNack")
//    public List<ReceiveMsg> pullNack() {
//        List<ReceiveMsg> receiveMsgs = pullMessageFeign.pullNack();
//        return receiveMsgs;
//    }

    /**
     * 获取指定用户的未读消息 Nack模式阅读
     * @param cid
     * @return
     */
    @GetMapping("/mqPullNack/{cid}")
    public Result<List<SendMsg>> pullNackbyUser(@PathVariable String cid) {
        List<SendMsg> mqMsgs = new ArrayList<>();
        List<ReceiveMsg> getResponses = pullMessageFeign.pullNack(cid);
        for (ReceiveMsg receiveMsg : getResponses) {
            SendMsg sendMsg = JSON.parseObject(receiveMsg.getMessage(), SendMsg.class);
            mqMsgs.add(sendMsg);
//            // Long类型比较不能用==
//            if (cid.equals(sendMsg.getReceiver())){
//                mqMsgs.add(sendMsg);
//            }
        }
        return new Result<List<SendMsg>>(true,StatusCode.OK,"Nack获取未读消息成功",mqMsgs);
    }

    /**
     * 获取指定用户的未读消息 ack模式阅读
     * @param cid
     * @return
     */
    @GetMapping("/mqPullAck/{cid}")
    public Result<List<SendMsg>> pullAckByUser(@PathVariable String cid) {
        List<SendMsg> mqMsgs = new ArrayList<>();
        List<ReceiveMsg> getResponses = pullMessageFeign.pullAck(cid);
        for (ReceiveMsg receiveMsg : getResponses) {
            SendMsg sendMsg = JSON.parseObject(receiveMsg.getMessage(), SendMsg.class);
            mqMsgs.add(sendMsg);
//            // Long类型比较不能用==
//            if (cid.equals(sendMsg.getReceiver())){
//                mqMsgs.add(sendMsg);
//            }
        }
        return new Result<List<SendMsg>>(true,StatusCode.OK,"Ack获取未读消息成功",mqMsgs);
    }


//    /**
//     * 获取指定好友的未读消息 Nack模式阅读
//     * @param uid
//     * @param fid
//     * @return
//     */
//    @GetMapping("/mqPullNack/{uid}/{fid}")
//    public Result<List<SendMsg>> pullNackByFriend(@PathVariable String uid, @PathVariable String fid) {
//
//        List<SendMsg> mqMsgs = new ArrayList<>();
//        List<ReceiveMsg> getResponses = pullMessageFeign.pullNack(uid);
//        for (ReceiveMsg receiveMsg : getResponses) {
//            SendMsg sendMsg = JSON.parseObject(receiveMsg.getMessage(), SendMsg.class);
//            if (uid.equals(sendMsg.getReceiver()) && fid.equals(sendMsg.getSender())){
//                mqMsgs.add(sendMsg);
//            }
//        }
//        return new Result<List<SendMsg>>(true,StatusCode.OK,"Nack获取未读消息成功",mqMsgs);
//    }
//
//    /**
//     * 获取指定好友的未读消息 ack模式阅读
//     * @param uid
//     * @param fid
//     * @return
//     */
//    @GetMapping("/mqPullAck/{uid}/{fid}")
//    public Result<List<SendMsg>> pullAckByFriend(@PathVariable String uid, @PathVariable String fid) {
//        List<SendMsg> mqMsgs = new ArrayList<>();
//        List<ReceiveMsg> getResponses = pullMessageFeign.pullAck(uid);
//        for (ReceiveMsg receiveMsg : getResponses) {
//            SendMsg sendMsg = JSON.parseObject(receiveMsg.getMessage(), SendMsg.class);
//            if (uid.equals(sendMsg.getReceiver()) && fid.equals(sendMsg.getSender())){
//                mqMsgs.add(sendMsg);
//            }
//        }
//        return new Result<List<SendMsg>>(true,StatusCode.OK,"Ack获取未读消息成功",mqMsgs);
//    }

}
